<template>
    <div>
        <div class="flex items-center pl-36px pt-26px pr-26px text-14px font-bold level-2-title">
            产品名称: <b>{{ props.ruleForm.name }}</b>
        </div>
        <div class="flex items-center ml-26px mr-26px mt-20px friendly-tips">
            <svg-icon size="18px"
                icon-class="information-2-fill"></svg-icon>为了保证产品的精准推广，前置词和后置词均不少于<el-text type="primary">4</el-text>个，不大于<el-text type="danger">10</el-text>个。主关键词需和当前产品相符，且只可添加一个，不建议使用带字母或数字的关键词。
        </div>
        <div class="pt-26px pl-26px pr-26px words-container">
            <el-row :gutter="26">
                <el-col :span="6">
                    <Area :rule-form="ruleForm" />
                </el-col>
                <el-col :span="6">
                    <FrontKeyword :rule-form="ruleForm" />
                </el-col>
                <el-col :span="6">
                    <MainKeyword :rule-form="ruleForm" />
                </el-col>   
                <el-col :span="6">
                    <BackKeyword :rule-form="ruleForm" />
                </el-col>
            </el-row>
        </div>
        <div class="flex items-center pl-36px pt-26px pr-26px text-14px font-bold level-2-title">
            自定义关键词
        </div>
        <CustomizeKeyword :rule-form="ruleForm" />
        <div class="pl-26px pb-40px">
            <el-button @click="handlePure">上一步</el-button>
            <el-button :loading="loading" type="primary" @click="handleNext">下一步</el-button>
        </div>
        <ConfirmWord v-model:isConfirmDialogVisible="isConfirmDialogVisible" :rule-form="ruleForm" @closeDialog="isConfirmDialogVisible = false" @confirm="handleConfirm" />
    </div>
</template>

<script setup lang="ts">
import CustomizeKeyword from './CustomizeKeyword.vue'
import Area from './Area.vue'
import FrontKeyword from './FrontKeyword.vue'
import MainKeyword from './MainKeyword.vue'
import BackKeyword from './BackKeyword.vue' 
import { countByValue,findMatchingElements,convertWord,generateCombinations,hasCommonItem,hasItemWithString,hasItem } from '@/utils/index'
import { violationStr } from '@/utils/checkStr'
import { confirmMessageBox } from '@/utils/elMessageBox'
import { CircleCloseFilled,WarningFilled } from '@element-plus/icons-vue'
import { deleteWordsCheckApi,sensitiveWordsCheckApi } from '@/api/b2b/index'
import ConfirmWord from './ConfirmWord.vue'

const props = defineProps<{
    modelValue: number
    ruleForm: any
}>()

// 使用 computed + watch 实现双向绑定效果
const step = ref(props.modelValue)

watch(
    () => props.modelValue,
    (newVal) => {
        if (typeof newVal === 'number') {
            step.value = newVal
        }
        console.log('newVal', props.ruleForm)
    }
)

const emit = defineEmits(['update:modelValue', 'step-2-complete'])

const isConfirmDialogVisible = ref(false)

const loading = ref(false)

function handlePure() {
    emit('update:modelValue', step.value)
}

async function handleNext() {
    loading.value = true
    //检测
    const isCheck = await check()
    if(isCheck){
        loading.value = false
        isConfirmDialogVisible.value = true
    }
}
function handleConfirm(){
    emit('step-2-complete', props.ruleForm)
}

async function check(){
    //前置词不能少于4个，不能大于10个
    //后置词不能少于4个，不能大于10个
    //主关键词只能选择一个，且必须选择一个.
    //自定义关键词不是必填项
    //自定义关键词不能包含“医用”、“医疗器械”、“手术器械”.
    //自定义关键词不能重复.
    //自定义关键词中必须包含主关键词,且不能与已有组合关键词（前置+主关键词+后置）重复
    const f = convertWord(props.ruleForm.frontWords)
    const b = convertWord(props.ruleForm.backWords)
    const m = convertWord(props.ruleForm.mainWords)
    const c = props.ruleForm.cusKeyword  //自定一/自定二

    const fwLength = countByValue(props.ruleForm.frontWords,1)
    const bwLength = countByValue(props.ruleForm.backWords,1)

    const cusKeywordArr = findMatchingElements(c, violationStr)    //检测自定义关键词中包含的违规词

    const frontKeyBack = generateCombinations(m.split('/'), f.split('/'), b.split('/'))   //前置+主词+后置
    const isSame  = hasCommonItem(frontKeyBack,c.split('/'))
    const isHasKeyword = hasItemWithString(c.split('/'),m.split('/'))
    const isKMSame = hasItem(c.split('/'),m)

    const Words = props.ruleForm.name + props.ruleForm.model + props.ruleForm.intro + f + props.ruleForm.keyword + b

    if(fwLength < 4 || fwLength > 10){
        confirmMessageBox(CircleCloseFilled, `前置词不能少于4个，不能大于10个`)
        loading.value = false
        return false
    }else if(!props.ruleForm.mainWords[0].label.length || !props.ruleForm.mainWords[0].value){
        confirmMessageBox(CircleCloseFilled, `主关键词只能选择一个，且必须选择一个`)
        loading.value = false
        return false
    }else if(bwLength < 4 || bwLength > 10){
        confirmMessageBox(CircleCloseFilled, `后置词不能少于4个，不能大于10个`)
        loading.value = false
        return false
    }else if(c.length && cusKeywordArr.length){
        confirmMessageBox(CircleCloseFilled, `自定义关键词不能包含“医用”、“医疗器械”、“手术器械”`)
        loading.value = false
        return false
    }else if(c.length && new Set(c.split('/')).size !== c.split('/').length){
        confirmMessageBox(CircleCloseFilled, `自定义关键词不能重复`)
        loading.value = false
        return false
    }else if(c.length && isSame){
        confirmMessageBox(CircleCloseFilled, `自定义关键词中不能与已有组合关键词（前置+主关键词+后置）重复`)
        loading.value = false
        return false
    } else if (c.length && !isHasKeyword) {
        confirmMessageBox(CircleCloseFilled, `自定义关键词中必须包含主关键词，且不能与已有组合关键词（前置+主关键词+后置）重复，未含主关键词：${m.split('/')[0]}`)
        loading.value = false
        return false
    } else if (c.length && isKMSame) {
        confirmMessageBox(CircleCloseFilled, `自定义关键词 与 主关键词不能重复`)
        loading.value = false
        return false
    }else{
        //必删词检测
        const isDelWord = await deleteWordsCheck(Words)
        if(isDelWord){
            //敏感词检测
            const isSenWord = await sensitiveWordsCheck(Words)
            if(isSenWord){
                return true
            }
        }
    }
}

async function sensitiveWordsCheck(content: string, type: string = 'content') {
    //检测敏感词
    try {
        const res: ResType = await sensitiveWordsCheckApi({
            txt: props.ruleForm.name,
            content: content
        })
        if (res.code === 200) {
            return true
        }
    } catch (error: any) {
        if (error.response && error.response.status === 405) {
            return new Promise((resolve, reject) => {
                confirmMessageBox(WarningFilled, `您发布的产品信息中含有类似虚假宣传、违禁词等敏感词，或含有本平台规定不得发布的医疗器械、 诊断试剂、药品等相关内容：(如："${error.response.data.message}")，从规避风险角度，建议修改后提交。`, '继续发布', '立即修改', () => {
                    loading.value = false
                    resolve(true)
                }, () => {
                    loading.value = false
                    handlePure()
                    reject(false)
                })
            })
        }
        return false
    }
}

async function deleteWordsCheck(words:string) {
    try {
        //必删词检测
        const res: ResType = await deleteWordsCheckApi({
            txt: words,
            content: props.ruleForm.content
        })
        if (res.code === 200) {
            return true
        }
    } catch (error: any) {
        if (error.response && error.response.status === 405) {
            return new Promise((resolve, reject) => {
                confirmMessageBox(CircleCloseFilled, `您发布的信息中含有虚假宣传、违禁词等敏感词，或含有本平台规定不得发布的医疗器械、 诊断试剂、药品等相关内容：(如：${error.response.data.message})，请检查修改后提交。`,'立即修改','', () => {
                    loading.value = false
                    handlePure()
                    resolve(false)
                }, () => {
                    loading.value = false
                    reject(false)
                })
            })
            
        }
    }
}
</script>

<style lang="scss" scoped>
.words-items__list {
    overflow: hidden;

    li {
        width: 50%;
        float: left;
        padding: 6px;

        p {
            font-size: 12px;
            line-height: 32px;
            border: 1px solid #dcdfe6;
            text-align: center;
            cursor: pointer;
            border-radius: 4px;

            input {
                width: 100%;
                height: 32px;
                text-align: center;
                background: none;
            }
        }

        &.active {
            p {
                color: var(--mainColor);
                border-color: var(--mainColor);
                background-color: #f3f7ff;
            }
        }
    }
}
.custom-input{
    .el-input{
        :deep(.el-input__wrapper){
            box-shadow: none !important;
            transition:all 0.3s;
        }
        &:hover{
            :deep(.el-input__wrapper){
                box-shadow: 0 0 0 1px var(--el-input-border-color,var(--el-border-color)) inset !important;
                transition:all 0.3s;
            }
        }
        
    }
    &.active{
        :deep(.el-input__wrapper){
            box-shadow: 0 0 0 1px var(--mainColor) inset !important;
        }
    }
}
</style>